package top.dyzmj.detty.core.utils.concurrent.future;

import top.dyzmj.detty.core.utils.concurrent.future.Future;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static java.util.Objects.isNull;

/**
 * 描述: 不允许取消的抽象 future 实现
 *
 * @author dongYu
 * @date 2021/11/26
 */
public abstract class AbstractFuture<V> implements Future<V> {

	@Override
	public V get() throws InterruptedException, ExecutionException {
		await();
		Throwable cause = cause();
		if (isNull(cause)) {
			return getNow();
		}
		if (cause instanceof CancellationException) {
			throw (CancellationException) cause;
		}
		throw new ExecutionException(cause);
	}


	@Override
	public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
		if (await(timeout, unit)) {
			Throwable cause = cause();
			if (isNull(cause)) {
				return getNow();
			}
			if (cause instanceof CancellationException) {
				throw (CancellationException) cause;
			}
			throw new ExecutionException(cause);
		}
		throw new TimeoutException();
	}
}
